#include <iostream>
#include <fstream>

#include "array.h"
#include "linked_list.h"

using namespace std;


//------------ Functions

bool lessThan(int x, int y);

//------------ Functors

class GreaterThan {
public:
	bool operator ()(int x, int y)
   {
      return x > y;
   }
};

//------------ Algorithms

template <typename ITERATOR, typename BINARY_PREDICATE>
int sort(ITERATOR first, ITERATOR last, BINARY_PREDICATE &f);


int main() {
	int a[] = {1, 3, 5, 4, 2};
	Array array(5, a);

	LinkedList linkedList;
	linkedList.insert(100);
	linkedList.insert(10);
	linkedList.insert(23);
	linkedList.insert(13);
	linkedList.insert(1);


	cout << "The Array: " << array << endl;
	cout << "The array: {";
	for (int i = 0; i < 5; i++)
		cout << a[i] << " ";
	cout << "}" << endl;
	cout << "The linked list: " << linkedList << endl;
	cout << endl;


	cout << "----- Sorting (using lessThan function)" << endl;
	sort(array.begin(), array.end(), lessThan);
	cout << "The Array: " << array << endl;
	sort(a, a+5, lessThan);
	cout << "The array: {";
	for (int i = 0; i < 5; i++)
		cout << a[i] << " ";
	cout << "}" << endl;
	sort(linkedList.begin(), linkedList.end(), lessThan);
	cout << "The linked list: " << linkedList << endl;
	cout << endl;

	cout << "----- Sorting (using GreaterThan functor)" << endl;
	GreaterThan greaterThan;
	sort(array.begin(), array.end(), greaterThan);
	cout << "The Array: " << array << endl;
	sort(a, a+5, greaterThan);
	cout << "The array: {";
	for (int i = 0; i < 5; i++)
		cout << a[i] << " ";
	cout << "}" << endl;
	sort(linkedList.begin(), linkedList.end(), greaterThan);
	cout << "The linked list: " << linkedList << endl;
	cout << endl;

	return 0;
}


//------------------ Algorithms

template <typename ITERATOR, typename BINARY_PREDICATE>
int sort(ITERATOR first, ITERATOR last, BINARY_PREDICATE &f)
{
   bool swapped;
   do
   {
      swapped = false;
      for (ITERATOR it = first; it != last; ++it)
      {
         ITERATOR next = it;
         ++next;
         if (next == last)
             break;

         if (f(*it, *next))
         {
            int temp = *it;
            *it = *next;
            *next = temp;
            swapped = true;
         }
      }
   }
   while (swapped);
   
   return 0;
}

//---------------- Functions
bool lessThan(int x, int y)
{
   return x < y;
}
